import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../utils/adapt.dart';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../components/banner.dart';
import '../components/channel.dart';
import '../components/floors.dart';
import '../components/floortitle.dart';
import '../components/recommend.dart';
import '../components/banner_list.dart';
import '../components/videolist.dart';
import 'package:provider/provider.dart';
import '../provider/playAudioList.dart';
import '../provider/audioProgress.dart';
import '../provider/currentRoute.dart';
import '../event_bus.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:percent_indicator/percent_indicator.dart';

class Index extends StatefulWidget {
  Index({Key? key}) : super(key: key);

  @override
  _IndexState createState() => _IndexState();
}

class _IndexState extends State<Index> {
  late AudioPlayer _audioPlayer;

  String _url =
      'https://m8.music.126.net/20210914122140/d137bdc5ae41e6705eac5bc6eedd5f67/ymusic/0fd6/4f65/43ed/a8772889f38dfcb91c04da915b301617.mp3';
  bool _canPlay = false;
  var playAudioList;
  var audioProgress;
  bool _barShow = true;
  bool _noPrev = false;
  bool _noNext = false;
  bool _isPlaying = false;
  var _atPlayRoute;
  bool _bl = false;
  void initAudio(url) async {
    int result = await _audioPlayer.play(url);
    if (result == 1) {
      _audioPlayer.onDurationChanged.listen((Duration d) {
        var _t = 0;
        var _cur = "$d".substring(2, 7);
        var _m = int.parse("$_cur".substring(0, 2));
        var _s = int.parse("$_cur".substring(3));
        var _total = _m * 60 + _s;
        audioProgress.setTotalTime(_total * 1000);
      });
    }
    _audioPlayer.onAudioPositionChanged.listen((Duration p) {
      var _t = 0;
      var _cur = "$p".substring(2, 7);
      var _m = int.parse("$_cur".substring(0, 2));
      var _s = int.parse("$_cur".substring(3));
      var _total = _m * 60 + _s;
      audioProgress.setCurrentTime(_total * 1000);
      eventbus.fire(new progressChange(_total)); // 播放进度改变发广播，告诉歌词滚动
    });
    _audioPlayer.onPlayerCompletion.listen((event) {
      var _index = playAudioList.getCurrentIndex;
      var length = playAudioList.getAudioList.length;
      var _isPlaying = _atPlayRoute.getCurrentIsPlaying;
      if (_index == length - 1) {
        var _position = Duration(
          minutes: 0,
          seconds: 0,
        );
        // seek
        _audioPlayer.seek(_position);
        _audioPlayer.resume();
      } else {
        // 歌曲播放完自动下一首的时候，不明原因的这里执行啦三次，所以用个开关限制下
        if (_bl) return;
        this.setState(() {
          _bl = true;
        });
        playAudioList.setCurrentIndex(_index + 1);
        var _list = playAudioList.getAudioList;
        var _id = _list[_index + 1]['id'];
        _getUrl(_id);
        var _duration = Duration(seconds: 2);
        Timer(_duration, () {
          this.setState(() {
            _bl = false;
          });
        });
      }
      if (_isPlaying) {
        if (_index == length - 1) {
          playAudioList.setCurrentIndex(_index);
          Navigator.pushReplacementNamed(context, "/audioplayer",
              arguments: {});
        } else {
          playAudioList.setCurrentIndex(_index + 1);
          Navigator.pushReplacementNamed(context, "/audioplayer",
              arguments: {});
        }
      }
    });

    _audioPlayer.onPlayerError.listen((msg) {
      print('播放器错误-audioPlayer error : $msg');
    });
  }

  void _changePlayState(bl) async {
    var _state = playAudioList.getCurrentState;
    playAudioList.setAudioState(!_state);
    if (bl) {
      _audioPlayer.resume();
    } else {
      _audioPlayer.pause();
    }
    this.setState(() {
      _isPlaying = !bl;
    });
  }

  @override
  void initState() {
    _audioPlayer = AudioPlayer();
    super.initState();
    eventbus.on<setAudioUrl>().listen((event) {
      initAudio(event.url);
    });
    eventbus.on<changeAudioState>().listen((event) {
      _changePlayState(event.state);
    });
    eventbus.on<setAudioSeek>().listen((event) {
      var _list = "${event.cur}".split(':');
      var _position = Duration(
        minutes: int.parse(_list[1]),
        seconds: int.parse("${_list[2]}".split(".")[0]),
      );
      // seek
      _audioPlayer.seek(_position);
    });
  }

  void _getUrl(id) async {
    var res = await getHttp('/song/url?id=$id');
    var data = res['data'][0];
    if (data['url'] == null) {
      EasyLoading.showError('该歌曲不可用！');
      const timeout = const Duration(seconds: 2);
      Timer(timeout, () {
        EasyLoading.dismiss();
        Navigator.pop(context);
      });
    } else {
      var url = data['url'].replaceAll('http', 'https');
      initAudio(url);
    }
  }

  void _playPrev(_list, _index) {
    var _id = _list[_index - 1]['id'];
    _getUrl(_id);
  }

  void _playNext(_list, _index) {
    var _id = _list[_index + 1]['id'];
    _getUrl(_id);
  }

  @override
  void deactivate() async {
    int result = await _audioPlayer.release();
    if (result == 1) {
      print('release success');
    } else {
      print('release failed');
    }
    super.deactivate();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _audioPlayer.dispose();
  }

  @override
  Widget build(BuildContext context) {
    playAudioList = Provider.of<PlayAudioList>(context);
    audioProgress = Provider.of<AudioProgress>(context);
    _atPlayRoute = Provider.of<atPlayRoute>(context);
    var index = playAudioList.getCurrentIndex;
    var length = playAudioList.getAudioList.length;
    return Scaffold(
        backgroundColor: Colors.white,
        floatingActionButton: length < 2
            ? null
            : FloatingActionButton(
                // backgroundColor: Color.fromRGBO(0, 1, 1, 0),
                onPressed: () {
                  this.setState(() {
                    _barShow = !_barShow;
                  });
                },
                child: CircularPercentIndicator(
                  radius: 56.0,
                  lineWidth: 8.w,
                  percent: audioProgress.getCurrentTime /
                              audioProgress.getTotalTime <
                          1
                      ? audioProgress.getCurrentTime /
                          audioProgress.getTotalTime
                      : 0,
                  center: AnimatedSwitcher(
                    duration: Duration(milliseconds: 500),
                    child: _barShow
                        ? Icon(
                            Icons.play_circle,
                            key: UniqueKey(),
                          )
                        : Icon(
                            Icons.list_alt,
                            key: UniqueKey(),
                          ),
                  ),
                  progressColor: Colors.green,
                ),
              ),
        appBar: AppBar(
          leading: Container(
            padding: EdgeInsets.only(left: Adapt.px(10)),
            child: Icon(Icons.face_outlined),
          ),
          leadingWidth: Adapt.px(40),
          title: Center(
            child: InkWell(
              onTap: () {
                Navigator.pushNamed(context, "/search");
              },
              child: Container(
                height: Adapt.px(72),
                padding: EdgeInsets.symmetric(horizontal: Adapt.px(20)),
                decoration: BoxDecoration(
                  color: Colors.blue[300],
                  borderRadius: BorderRadius.circular(Adapt.px(20)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "搜索你喜欢的歌曲",
                      style: TextStyle(fontSize: Adapt.px(28)),
                    ),
                    Icon(Icons.zoom_in_outlined)
                  ],
                ),
              ),
            ),
          ),
          actions: [
            Container(
              margin: EdgeInsets.only(right: Adapt.px(24)),
              child: Icon(Icons.ac_unit),
            )
          ],
        ),
        body: Stack(
          children: [
            ListView(
              // addAutomaticKeepAlives: true,
              children: [
                MyBanner(),
                Channel(),
                Floors(),
                FloorTitle(
                  "热门歌手",
                  callback: () {
                    Navigator.pushNamed(context, '/allsingers');
                  },
                ),
                Recommend(),
                Floors(),
                FloorTitle(
                  "推荐新歌",
                  callback: () {
                    Navigator.pushNamed(context, '/recommendpage');
                  },
                ),
                BannerList(),
                Floors(),
                FloorTitle("推荐MV", callback: () {
                  Navigator.pushNamed(context, '/videolist');
                }),
                VideoList(),
                Container(
                  height: Adapt.px(200),
                  child: Center(
                    child: Text(
                      '---我是一根底线---',
                      style: TextStyle(fontSize: 30.w),
                    ),
                  ),
                ),
              ],
            ),
            Positioned(
              bottom: -40.h,
              right: -40.h,
              child: length < 2
                  ? Text("")
                  : AnimatedContainer(
                      duration: Duration(milliseconds: 500),
                      width: _barShow ? 300.w : 0.w,
                      height: _barShow ? 300.w : 0.w,
                      decoration: BoxDecoration(
                        color: Color.fromARGB(185, 160, 170, 150),
                        borderRadius: BorderRadius.circular(200.w),
                      ),
                      child: Stack(
                        children: [
                          Align(
                            alignment: Alignment(-1.1, 0.1),
                            child: IconButton(
                              onPressed: () {
                                var _index = playAudioList.getCurrentIndex;
                                if (_index == 0) {
                                  this.setState(() {
                                    _noPrev = true;
                                  });
                                  EasyLoading.showToast('已经是第一个啦');
                                } else {
                                  playAudioList.setCurrentIndex(_index - 1);
                                  var _list = playAudioList.getAudioList;
                                  _playPrev(_list, _index);
                                }
                              },
                              icon: Icon(
                                Icons.skip_previous,
                                size: 80.w,
                                color: Colors.blue,
                              ),
                            ),
                          ),
                          Align(
                            alignment: Alignment(-0.78, -0.78),
                            child: IconButton(
                              onPressed: () {
                                var _bl = playAudioList.getCurrentState;
                                _changePlayState(_bl);
                              },
                              icon: Icon(
                                _isPlaying
                                    ? Icons.play_circle_fill
                                    : Icons.pause,
                                size: 80.w,
                                color: Colors.blue,
                              ),
                            ),
                          ),
                          Align(
                            alignment: Alignment(0.1, -1.1),
                            child: IconButton(
                              onPressed: () {
                                var _index = playAudioList.getCurrentIndex;
                                var length = playAudioList.getAudioList.length;
                                if (_index == length - 1) {
                                  this.setState(() {
                                    _noNext = true;
                                  });
                                  EasyLoading.showToast('已经是最后一个啦');
                                } else {
                                  var _list = playAudioList.getAudioList;
                                  playAudioList.setCurrentIndex(_index + 1);
                                  _playNext(_list, _index);
                                }
                              },
                              icon: Icon(
                                Icons.skip_next,
                                size: 80.w,
                                color: Colors.blue,
                              ),
                            ),
                          ),
                        ],
                      )),
            )
          ],
        ));
  }
}
